//
//  STCalendarKitView.m
//  STNewTools
//
//  Created by stoneobs on 2017/7/20.
//  Copyright © 2017年 stoneobs. All rights reserved.
//

#import "STCalendarKitView.h"

static NSString * const STCalendarKitMainCollectionCellIdentifier = @"STCalendarKitMainCollectionCellIdentifier";
@interface STCalendarKitView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,weak)id<STCalendarKitViewDlegate>            delegate;

@property(nonatomic,assign)STCalendarKitViewType                     type;

@property(nonatomic,strong)UICollectionView                          *collectionView;

@property(nonatomic,strong)NSMutableArray<STCalendarKitMonthModel*>    *datasouce;

@property(nonatomic,strong)STCalendarKitDayModel         *selectedModel;//存放选中的model，其他被选中，则全部取消选择，只保留一个选择
@property(nonatomic,strong)NSIndexPath            *currentMainIndexPath;//当前位置

@end
@implementation STCalendarKitView
- (void)dealloc
{
    NSLog(@"STCalendarKitView  dealloc");
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    return [self initWithFrame:CGRectZero delegate:nil];
}
- (instancetype)initWithFrame:(CGRect)frame{

    return [self initWithFrame:frame delegate:nil];
}
- (instancetype)initWithFrame:(CGRect)frame delegate:(id<STCalendarKitViewDlegate>)delegate{

    if (self == [super initWithFrame:frame]) {
        
        self.delegate = delegate;
        
       
    }
    return self;

}

- (void)layoutSubviews
{
    [self configSubView];
    [self createData];
}

#pragma mark --构造数据
- (void)createData{
    

    self.datasouce = [NSMutableArray new];
    if ([self.delegate respondsToSelector:@selector(numberOfAutoAddDataSouceNumbersFromCalendarKitView:)]) {
        _autoAddDataSouceNumbers = [self.delegate numberOfAutoAddDataSouceNumbersFromCalendarKitView:self];
    }
    
    _autoAddDataSouceNumbers = _autoAddDataSouceNumbers?_autoAddDataSouceNumbers:12;
    
    if ([self.delegate respondsToSelector:@selector(numberOfAutoAddDataSouceLeftMonthsFromCalendarKitView:)]) {
        _autoAddDataSouceLeftMonths = [self.delegate numberOfAutoAddDataSouceLeftMonthsFromCalendarKitView:self];
    }
    _autoAddDataSouceLeftMonths = _autoAddDataSouceLeftMonths?_autoAddDataSouceLeftMonths:4;
    
    NSDate * date = [NSDate localCurrentDate];
    
    NSDateFormatter * formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"YYYY-MM-dd";
    //日历初始月份,
    NSDate * originDate = [formater dateFromString:STCalendarKitViewBeginDateString].localDate;
    NSDateComponents * originCom = [NSCalendar comWithDate:originDate];
    
    NSDateComponents * todayCom = [NSCalendar comWithDate:date];
    
    NSInteger lastNum = 12*(todayCom.year - originCom.year) + todayCom.month - originCom.month;
    
    NSArray<STCalendarKitMonthModel*> *lastMonths = [[STCalendarKitMonthManger defult] calculatelastMonthsWithDate:date nums:lastNum];
    
    
    
    NSArray<STCalendarKitMonthModel*> *nextMonths = [[STCalendarKitMonthManger defult] calculateNextMonthsWithDate:date nums:_autoAddDataSouceNumbers-lastMonths.count];
    self.currentMonthModel = nextMonths.firstObject;
    
    NSInteger i = 0;
    for (STCalendarKitDayModel * model in nextMonths.firstObject.allDaysArray) {
        
        if ([model.date.yyyyMMddByLineWithDate isEqualToString:[NSDate localCurrentDate].yyyyMMddByLineWithDate]) {
            break;
        }
        i ++;
    }
    self.slectedIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
    [self.datasouce addObjectsFromArray:lastMonths];
    [self.datasouce addObjectsFromArray:nextMonths];
  
    //代理
    if ([self.delegate respondsToSelector:@selector(calendarKitViewDidCalculatorData:willDisplayArray:)]) {
        [self.delegate calendarKitViewDidCalculatorData:self willDisplayArray:self.datasouce];
    }

    


    [self scrollViewDidEndDecelerating:self.collectionView];
}
#pragma mark --Geter And Seter
- (UICollectionView *)collectionView{

    if (!_collectionView) {
        
        UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
        [flow setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        flow.minimumLineSpacing = 0;
        flow.minimumInteritemSpacing = 0;
        flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height) collectionViewLayout:flow];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[STCalendarKitMainCollectionViewCell class]
            forCellWithReuseIdentifier:STCalendarKitMainCollectionCellIdentifier];

    }
    return _collectionView;

}
#pragma mark --SubView
- (void)configSubView{
    
    [self addSubview:self.collectionView];
    

    
}
#pragma --mark UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.datasouce.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.width, self.height);
}
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    STCalendarKitMainCollectionViewCell * item = [collectionView dequeueReusableCellWithReuseIdentifier:STCalendarKitMainCollectionCellIdentifier forIndexPath:indexPath];
    item.monthModel = self.datasouce[indexPath.section];
    [item setButtonAction:^(UIButton * button, NSIndexPath * itemIndexPath){
        [weakSelf buttonAction:button mainItemIndexPath:indexPath itemIndexPath:itemIndexPath];
    }];
    return item;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    STCalendarKitMainCollectionViewCell * item = (STCalendarKitMainCollectionViewCell*)cell;
    [item reloadData];
}
#pragma --mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}

#pragma mark --处理按钮点击事件的逻辑
- (void)buttonAction:(UIButton*)button mainItemIndexPath:(NSIndexPath*)mainItemIndexPath  itemIndexPath:(NSIndexPath*)itemIndexPath{

    BOOL originIsSlected = self.selectedModel.isSelected;
    self.selectedModel.isSelected = NO;
    STCalendarKitDayModel * model = self.datasouce[mainItemIndexPath.section].allDaysArray[itemIndexPath.row];
    if (model == self.selectedModel) {
        //如果再次点击已被点击过的cell，那么只是切换点击和非点击状态，而不是统一变为非点击。
        self.selectedModel.isSelected = !originIsSlected;
    }
    self.selectedModel = model;
    self.slectedIndexPath = itemIndexPath;
    [self.collectionView reloadItemsAtIndexPaths:@[mainItemIndexPath]];
    
    //响应delegate
    if (model.isLastMonth) {
        if ([self.delegate respondsToSelector:@selector(calendarKitViewDidclicTheLastMonthItem:mainIndexPath:itemIndexPath:copyDayModel:)]) {
            [self.delegate calendarKitViewDidclicTheLastMonthItem:self mainIndexPath:mainItemIndexPath itemIndexPath:itemIndexPath copyDayModel:[model copy]];
        }
        return;
    }
    if (model.isThisMonth) {
        if ([self.delegate respondsToSelector:@selector(calendarKitViewDidclicTheCurrentMonthItem:mainIndexPath:itemIndexPath:copyDayModel:) ]) {
            [self.delegate calendarKitViewDidclicTheCurrentMonthItem:self mainIndexPath:mainItemIndexPath itemIndexPath:itemIndexPath copyDayModel:[model copy]];
        }
        return;
    }
    if (model.isNextMonth) {
        if ([self.delegate respondsToSelector:@selector(calendarKitViewDidclicTheNextMonthItem:mainIndexPath:itemIndexPath:copyDayModel:)]) {
            [self.delegate calendarKitViewDidclicTheNextMonthItem:self mainIndexPath:mainItemIndexPath itemIndexPath:itemIndexPath copyDayModel:[model copy]];
        }
        return;
    }
   
   
}

#pragma mark --UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == self.collectionView) {
        NSInteger num = scrollView.contentOffset.x / ([UIScreen mainScreen].bounds.size.width - 0.00001) ;
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:num];
        STCalendarKitMonthModel * model = self.datasouce[num];
        if (_currentMainIndexPath == indexPath) {
            return;
        }
        self.currentMainIndexPath  = [NSIndexPath indexPathForRow:0 inSection:num];
        
        
        if ([self.delegate respondsToSelector:@selector(calendarKitViewDidEndScroll:mainIndexPath:copyMonthModel:)]) {
            [self.delegate calendarKitViewDidEndScroll:self mainIndexPath:[NSIndexPath indexPathForRow:0 inSection:num]
                                        copyMonthModel:[model copy]];
        }
    }

}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    


}
#pragma mark --public Method
- (void)reloadData{
    [self.collectionView reloadData];
}
- (void)scrollTodate:(NSDate *)date{
    STCalendarKitDayModel * model = self.datasouce.lastObject.allDaysArray.lastObject;
    if ([date timeIntervalSince1970]> [model.date timeIntervalSince1970]) {
        NSLog(@"该日的数据还未加载，不允许滑动");
        return;
    }
    NSInteger index = 99999;
    for (int i = 0; i<self.datasouce.count; i++) {
        if ([date.yyyyMMByLineWithDate isEqualToString:self.datasouce[i].currentMonthDate.yyyyMMByLineWithDate]) {
            index = i;
            break;
        }
    }
    if (index == 99999) {
        NSLog(@"该日的数据数据源中不存在，不允许滑动");
        return;
    }
    //滑动
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    [self scrollViewDidEndDecelerating:self.collectionView];
}
- (void)setSelected:(BOOL)selected fromDate:(NSDate *)date{

    NSInteger mainIndex = 99999;
    for (int i = 0; i<self.datasouce.count; i++) {
        if ([date.yyyyMMByLineWithDate isEqualToString:self.datasouce[i].currentMonthDate.yyyyMMByLineWithDate]) {
            mainIndex = i;
            break;
        }
    }
    if (mainIndex != 99999) {
        STCalendarKitMonthModel * monthModel = self.datasouce[mainIndex];
        for (int k = 0; k< monthModel.allDaysArray.count; k++) {
            STCalendarKitDayModel * dayModel = monthModel.allDaysArray[k];
            if ([dayModel.date.yyyyMMddByLineWithDate isEqualToString:date.yyyyMMddByLineWithDate]) {
                dayModel.isSelected = selected;
                [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:mainIndex]]];
                break;
            }
        }
    }
}
- (void)scrollToNextMonth{

    NSInteger num = self.currentMainIndexPath.section;
    if (num == self.datasouce.count - 1) {
        return;
    }
    CGRect test = CGRectMake(self.collectionView.contentOffset.x + self.width, 0, [UIScreen mainScreen].bounds.size.width, self.height);
    [self.collectionView performBatchUpdates:^{
        [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:num + 1]];
    } completion:^(BOOL finished) {
        [self.collectionView scrollRectToVisible:test animated:YES];
       // [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x + self.width, 0) animated:YES];
        
    }];


}
- (void)scrollToLastMonth{
    
    NSInteger num = self.currentMainIndexPath.section;
    if (num == 0) {
        return;
    }
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:num - 1] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    [self scrollViewDidEndDecelerating:self.collectionView];
}
@end
